renderUsername()

checkLogin()

registerLogout()
//get数据
async function getData() {
    const res = await axios.get("/students")

    //渲染数据
    /*
    <tr>
        <td>张杰</td>
        <td>20</td>
        <td>男</td>
        <td>第2组</td>
        <td>10000</td>
        <td>13000</td>
        <td>北京北京市东城区</td>
        <td>
            <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
            <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
        </td>
    </tr>
     */

    const html = res.data.map(v => {
        const { name, age, gender, group, hope_salary, salary, province, city, area, id } = v
        
        return `
        <tr>
            <td>${name}</td>
            <td>${age}</td>
            <td>${gender === 0 ? "男" : "女"}</td>
            <td>第${group}组</td>
            <td>${hope_salary}</td>
            <td>${salary}</td>
            <td>${province + city + area}</td>
            <td data-id='${id}'>
                <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
            </td>
        </tr>
        `
    }).join('')

    document.querySelector(".list").innerHTML = html
    document.querySelector(".total").innerHTML = res.data.length
}
getData()

//点击弹框 Modal show()
//省市区渲染
//新增数据(form形式) 收集 --> 转换 --> 提交
//提示弹窗
const modalDom = document.querySelector("#modal")
const modal = new bootstrap.Modal(modalDom)

document.querySelector("#openModal").addEventListener("click", () => {
    modal.show()
})
//省市区联动
const proSelect = document.querySelector('[name=province]')
const citySelect = document.querySelector('[name=city]')
const areaSelect = document.querySelector('[name=area]')

async function initSelect() {
    const proRes = await axios.get('/api/province')

    const proHtml = proRes.list.map(v => {
        return `<option value="${v}>${v}</option>`
    }).join('')

    proSelect.innerHTML = `<option value="">--请选择--</option>${proHtml}`

    proSelect.addEventListener('change', async () => {
        const cityRes = await axios.get('/api/city', {
            params: {
                pname:proSelect.value
            }
        })
        const cityHTML = cityRes.list.map(v => {
            return `<option value="${v}>${v}</option>`
        }).join('')
        citySelect.innerHTML = `<option value="">--请选择--</option>${cityHTML}`
        areaSelect.innerHTML = `<option value="">--地区--</option>`
    })

    citySelect.addEventListener('change', async () => {
        const areaRes = await axios.get('/api/area', {
            params: {
                cname: citySelect.value,
                pname: proSelect.value
            }
        })
        const areaHTML = areaRes.list.map(v => {
            return `<option value="${v}>${v}</option>`
        }).join('')
        areaSelect.innerHTML = `<option value="">--请选择--</option>${areaHTML}`
    })
}

initSelect()

//弹窗 确定按钮的点击事件
document.querySelector("#submit").addEventListener("click", () => {
    if (modalDom.dataset.id) {
        //新增学生
        addStudent()
    } else {
        //编辑学生
        saveEdit()
    }
})
async function addStudent() {
    console.log("添加");
    //数据收集 转换 提交
    const form = document.querySelector("#form")
    const data = serialize(form, { empty: true, hash: true })
    console.log(data);
    data.age = +data.age
    data.gender = +data.gender
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    data.group = +data.group
    console.log(data);

    try {
        const res = await axios.post("/students", data)
        showToast(res.message)
    }catch (err) {
        //新增失败
        showToast(err.response.data.message)
    }
    modal.hide()
}

//删除 编辑 点击事件
document.querySelector(".list").addEventListener("click", (e) => {
    if (e.target.classList.contains("bi-trash")) {
        const id = e.target.parentNode.parentNode.dataset.id

        delStudent(id)
    }
//编辑
     if (e.target.classList.contains("bi-pen")) {
        const id = e.target.parentNode.parentNode.dataset.id

        editStudent(id)
    }
})
//删除
async function delStudent(id) {
    const res = await axios.delete(`/students/${id}`)

    showToast(res.message)

    //重新渲染数据
    getData()
}

//编辑
//重置弹窗
document.querySelector("#openModal").addEventListener("click", () => {
    // console.log(12345678);
    //修改标题
    document.querySelector(".modal-title").innerText = "编辑学生信息"
    //表单重置
    document.querySelector("#form").reset()
    //省市区重置
    citySelect.innerHTML = "<option value=''>---城市---</option>"
    areaSelect.innerHTML = "<option value=''>---地区---</option>"
    //删除自定义属性
    modalDom.dataset.id = ""

    modal.show()
})
async function editStudent(id) {
    const res = await axios.get(`/students/${id}`)

    //修改标题
    document.querySelector(".modal-title").innerText = "修改学生信息"
    const keyArr = ["name", "age", "group", "hope_salary", "salary"]
    keyArr.forEach(key => {
        document.querySelector(`[name=${key}]`).value = res.data[key]
    })

    //设置性别 0 男 1 女
    const { gender } = res.data
    const chks = document.querySelectorAll('[name=gender]')
    chks[gender].checked = true

    //设置籍贯
    const { province, city, area } = res.data

    //设置省
    const proRes = await axios.get("/api/province")
    const proHtml = proRes.list.map(v => {
        return `<option value="${v}">${v}</option>`
    }).join('')
    proSelect.innerHTML = `<option value="">--省份--</option><option value="${province}">${province}</option>${proHtml}`
    proSelect.value = province
    //设置市
    const cityRes = await axios.get("/api/city",{
        params: {
            pname:province
        }
    })
    const cityHtml = cityRes.list.map(v => {
        return `<option value="${v}">${v}</option>`
    }).join('')
    // console.log(city);
    citySelect.innerHTML = `<option value="">--城市--</option><option value="${city}">${city}</option>${cityHtml}`
    citySelect.value = city

    //设置区
    const areaRes = await axios.get('/api/area',{
        params: {
            pname: province,
            cname:city
        }
    })
    const areaHtml = areaRes.list.map(v => {
        return `<option value="${v}">${v}</option>`
    }).join('')
    areaSelect.innerHTML = `<option value="">--地区--</option><option value="${area}">${area}</option>${areaHtml}`
    areaSelect.value = area
    //弹窗
    modal.show()

    //保存学员id--编辑id
    modalDom.dataset.id = id
}


//抽取编辑函数 保存更改
async function saveEdit() {
    console.log("编辑");
    //数据收集 转换 提交
    const form = document.querySelector("#form")
    const data = serialize(form, { empty: true, hash: true })

    data.age = +data.age
    data.gender = +data.gender
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    data.group = +data.group
    console.log(data);

    try {
        const res = await axios.put(`/students/${modalDom.dataset.id}`, data)
        showToast(res.message)
        getData()
    }catch (err) {
        //修改失败
        showToast(err.response.data.message)
    }
    modal.hide()
}